package cn.hxzy.common.handler;


import cn.hxzy.common.util.ThreadLocalUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //开辟了一个线程1，把当前登录的用户对象存放到此线程中
        try {
            String token = request.getHeader("Authorization");
            if(StringUtil.isNullOrEmpty(token)){
                throw new RuntimeException("token为空");
            }
        } catch (Exception e) {
//            throw new RuntimeException(e);
            response.setStatus(401);
            return false;
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.removeUser();
    }
}
